package com.learn.springboot.util;

import com.learn.springboot.domain.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * 密码助手
 *
 * @author dyz
 * @date 2020/6/13 17:21
 */
public class PasswordHelper {
    private final RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    /**
     * 算法名称：基础散列算法
     */
    public static final String ALGORITHM_NAME = "md5";
    /**
     * 哈希的迭代：自定义散列次数
     */
    public static final int HASH_ITERATIONS = 2;

    public void encryptPassword(User user) {
        // 随机字符串作为salt因子，实际参与运算的salt我们还引入其它干扰因子
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(ALGORITHM_NAME, user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()), HASH_ITERATIONS).toHex();
        user.setPassword(newPassword);
    }
}
